package cn.com.callback

import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

/**
 *
 * @Title: main.java.cn.com.callback-autoGetDocumentRes
 * @Description:ngsapitask-pa 系统API接口开发Demo，重点关注业务逻辑部分
 * @Author: 86173* @Date 2022/2/14 19:06
 *
 */
class autoGetDocumentRes implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoGetDocumentRes.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String body) {
        boolean runflag = true;

        while (runflag) {
            try {
                // 获取发送所需要的Token
                String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");

                JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=SMS", "UTF-8", 5000, 0));
                String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

                // 调用地址
                String sendURL = KHDBConfig.getAPIURL(eliteBean, "PA-SMS-queryUrl") + "/" + KHDBConfig.getParam(eliteBean, "SMS-SI") + "?access_token=" + access_token + "&request_id=" + String.valueOf(System.currentTimeMillis());
                log.debug("请求URL：" + sendURL);

                // 处理头文件
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("Accept", "application/json");
                headerMap.put("Content-Type", "application/json");

                String postResult = Util.doHttpGetUseHead(sendURL, "UTF-8", 120000, 0, headerMap);
                log.debug("返回请求体：" + postResult);

                JSONObject resultJson = JSONObject.fromObject(postResult);
                String ret = resultJson.getString("ret");
                if (ret == "0") {
                    JSONArray jsonArray = resultJson.getJSONObject("data").getJSONArray("result");
                    int dataArrayLen = jsonArray.size();

                    for (int i = 0; i < dataArrayLen; i++) {
                        def RequestID = jsonArray.getJSONObject(i).getString("RequestID");
                        def ReportResultID = jsonArray.getJSONObject(i).getString("ReportResultID");
                        def SubmitResultDescription = jsonArray.getJSONObject(i).getString("SubmitResultDescription");
                        def ResultType = jsonArray.getJSONObject(i).getString("ResultType");
                        def SenderID = jsonArray.getJSONObject(i).getString("SenderID");
                        def SubmitTime = jsonArray.getJSONObject(i).getString("SubmitTime");
                        def ReportTime = jsonArray.getJSONObject(i).getString("ReportTime");
                        def SubmitResultID = jsonArray.getJSONObject(i).getString("SubmitResultID");
                        def ReportResultDescription = jsonArray.getJSONObject(i).getString("ReportResultDescription");
                        def TotalNumber = jsonArray.getJSONObject(i).getString("TotalNumber");
                        def MessageID = jsonArray.getJSONObject(i).getString("MessageID");
                        def SequenceID = jsonArray.getJSONObject(i).getString("SequenceID");

                        String selectSQL = "select rec_guid from pa_documentout_result where requestid='" + RequestID + "'";
                        List documentout_result = eliteBean.chaxun_sql(selectSQL, "dataSource");
                        int documentout_size = documentout_result.size();
                        log.debug("是否存在条数：" + documentout_size);

                        if (documentout_size > 0) {
                            String rec_guid = documentout_result.get(0).get("rec_guid");
                            String updateSQL = "update pa_documentout_result set del_falg='1' where rec_guid='" + rec_guid + "'";
                            int updateRow = eliteBean.update(updateSQL, "dataSource");
                            log.debug("本次更新数据：" + rec_guid + "|" + updateRow);
                        }

                        String insertSQL = "INSERT INTO pa_documentout_result(rec_guid, requestid, reportresultid, submitresultdescription, resulttype, senderid, submittime, reporttime, submitresultid, reportresultdescription, totalnumber, messageid, sequenceid ,del_falg) VALUES (uuid(), '" + RequestID + "', '" + ReportResultID + "', '" + SubmitResultDescription + "', '" + ResultType + "', '" + SenderID + "', '" + SubmitTime + "', '" + ReportTime + "', '" + SubmitResultID + "', '" + ReportResultDescription + "', '" + TotalNumber + "', '" + MessageID + "', '" + SequenceID + "','0')";
                        int insertRow = eliteBean.update(insertSQL, "dataSource");
                        log.debug("本次新增数据：" + RequestID + "|" + +insertRow);

                        log.debug("本次发送RequestID:"+RequestID+"本次发送状态:"+ReportResultID);
                        //20240919 如果发送失败 ，返回限制配额，将status 改为-1
                        if (!ReportResultID.equals("0") && !ReportResultDescription.equals("升级富信发送成功")){
                           eliteBean.update("Update Documentout Set Status ='-1', Failcode = '" + ReportResultID + "', Faildescription = '" + ReportResultDescription + "'  Where MSGID='"+RequestID+"'  ","dataSource");
                        }
                    }






                    if (dataArrayLen == 0) {
                        runflag = false;
                    }

                    log.debug("本来获取结果处理完成.runflag:" + runflag);
                }

            } catch (Exception e) {
                log.error("自动获取短信平台结果异常-:" + e.getMessage());
            }
        }
    }
}
